import os
from os import path
import urllib.request
from datetime import datetime, timedelta

class cache():
	def download(url, fname, timeout = 5):
		fromcache = False
		
		if path.isfile(fname):
			time = datetime.fromtimestamp(path.getmtime(fname))
			delta = datetime.now() - time
			if (delta < timedelta(minutes = timeout)):
				fromcache = True
			
		if fromcache == False:
			urllib.request.urlretrieve(url, fname)
			
		return fromcache


	def get(fname, timeout = 5):
		fromcache = False
		
		if path.isfile(fname):
			time = datetime.fromtimestamp(path.getmtime(fname))
			delta = datetime.now() - time
			if (delta < timedelta(minutes = timeout)):
				fromcache = True
			
		if fromcache == False:
			return None

		with open(fname, "rt") as f:
			s = f.read()
			
		return s

	def add(fname, s):
		with open(fname, "wt") as f:
			f.write(s)
			
		return s
